const app = getApp()

Page({
  data: {
    recordId: null,
    result: {},
    showQuestionDetail: false,
    currentQuestionDetail: null,
    loading: true
  },

  onLoad(options) {
    const { record_id } = options
    this.setData({ recordId: record_id })
    this.loadExamResult()
  },

  // 加载考试结果
  loadExamResult() {
    wx.showLoading({ title: '加载结果中...' })

    wx.request({
      url: `${app.globalData.baseUrl}/exams/result/${this.data.recordId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          const result = res.data.data
          
          // 计算正确率
          result.accuracy = Math.round((result.correct_count / result.total_questions) * 100)
          
          this.setData({ 
            result: result,
            loading: false
          })
          
          wx.hideLoading()
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('加载考试结果失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        wx.hideLoading()
      }
    })
  },

  // 查看证书
  viewCertificate() {
    if (this.data.result.certificate) {
      wx.navigateTo({
        url: `/pages/certificate-detail/certificate-detail?id=${this.data.result.certificate.id}`
      })
    }
  },

  // 下载证书
  downloadCertificate() {
    if (!this.data.result.certificate) return
    
    wx.showLoading({ title: '生成证书中...' })
    
    wx.request({
      url: `${app.globalData.baseUrl}/certificates/${this.data.result.certificate.id}/download`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          const { download_url } = res.data.data
          
          wx.downloadFile({
            url: download_url,
            success: (downloadRes) => {
              if (downloadRes.statusCode === 200) {
                wx.saveImageToPhotosAlbum({
                  filePath: downloadRes.tempFilePath,
                  success: () => {
                    wx.showToast({
                      title: '证书已保存到相册',
                      icon: 'success'
                    })
                  },
                  fail: (err) => {
                    console.error('保存证书失败:', err)
                    wx.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              }
            },
            fail: (err) => {
              console.error('下载证书失败:', err)
              wx.showToast({
                title: '下载失败',
                icon: 'none'
              })
            }
          })
        } else {
          wx.showToast({
            title: res.data.message || '下载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('获取下载链接失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 查看题目详情
  viewQuestionDetail(e) {
    const index = e.currentTarget.dataset.index
    const question = this.data.result.questions[index]
    
    this.setData({
      currentQuestionDetail: question,
      showQuestionDetail: true
    })
  },

  // 关闭题目详情
  closeQuestionDetail() {
    this.setData({
      showQuestionDetail: false,
      currentQuestionDetail: null
    })
  },

  // 重新考试
  retakeExam() {
    wx.showModal({
      title: '确认重新考试',
      content: '确定要重新参加该考试吗？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/exam-detail/exam-detail?id=${this.data.result.exam_id}&start=true`
          })
        }
      }
    })
  },

  // 返回考试列表
  goToExams() {
    wx.switchTab({
      url: '/pages/exams/exams'
    })
  },

  // 查看排行榜
  goToLeaderboard() {
    wx.navigateTo({
      url: '/pages/leaderboard/leaderboard'
    })
  },

  // 获取题目类型文本
  getQuestionTypeText(type) {
    const typeMap = {
      'single': '单选题',
      'multiple': '多选题',
      'true_false': '判断题'
    }
    return typeMap[type] || '未知类型'
  },

  // 获取选项样式类
  getOptionClass(optionKey) {
    if (!this.data.currentQuestionDetail) return ''
    
    const { user_answer, correct_answer } = this.data.currentQuestionDetail
    const isUserAnswer = user_answer && user_answer.includes(optionKey)
    const isCorrectAnswer = correct_answer && correct_answer.includes(optionKey)
    
    if (isUserAnswer && isCorrectAnswer) {
      return 'correct'
    } else if (isUserAnswer && !isCorrectAnswer) {
      return 'incorrect'
    } else if (isCorrectAnswer) {
      return 'correct'
    }
    
    return ''
  }
}) 